package com.fast.cron.db;

import com.fast.cron.common.config.PropConfigManager;
import com.zaxxer.hikari.HikariConfig;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * Hikari 数据源管理工具类
 *
 * @author :leo.jie
 * @version :v1.0
 * @date :2018/9/29 11:47
 */
public class HikariDataSourceHelper {

    private static HikariConfig config = new HikariConfig();
    private static PropConfigManager propConfigManager = PropConfigManager.build("fast-cron-db.properties");
    private static com.zaxxer.hikari.HikariDataSource dataSource;

    static {
        config.setJdbcUrl(propConfigManager.getProperty(DataSourceConfig.URL));
        config.setUsername(propConfigManager.getProperty(DataSourceConfig.USER));
        config.setPassword(propConfigManager.getProperty(DataSourceConfig.PW));
        config.setMinimumIdle(propConfigManager.getInteger(DataSourceConfig.MIN_IDLE));
        config.setMaximumPoolSize(propConfigManager.getInteger(DataSourceConfig.MAX_POOL_SIZE));
        config.setIdleTimeout(propConfigManager.getInteger(DataSourceConfig.IDLE_TIMEOUT));
        config.setPoolName(propConfigManager.getProperty(DataSourceConfig.POOL_NAME));
        config.setConnectionTimeout(propConfigManager.getLong(DataSourceConfig.CONNECT_TIME_OUT));
        config.setMaxLifetime(propConfigManager.getLong(DataSourceConfig.MAX_LIFETIME));
        dataSource = new com.zaxxer.hikari.HikariDataSource(config);
    }

    private static class DataSourceConfig {
        private static final String URL = "mysql.url";
        private static final String USER = "mysql.username";
        private static final String PW = "mysql.password";
        private static final String MIN_IDLE = "dataSource.minimumIdle";
        private static final String MAX_POOL_SIZE = "dataSource.MaximumPoolSize";
        private static final String IDLE_TIMEOUT = "dataSource.idleTimeout";
        private static final String POOL_NAME = "dataSource.poolName";
        private static final String CONNECT_TIME_OUT = "dataSource.connectionTimeout";
        private static final String MAX_LIFETIME = "dataSource.MaxLifetime";
    }

    public static Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }
}
